﻿/*
 * Created by SharpDevelop.
 * User: domi
 * Date: 2014/1/14
 * Time: 23:26
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Net;

namespace FileInsert
{
	class Program
	{
		private static Encoding encoding;
		
		public static void Main(string[] args)
		{
			Console.WriteLine("请输入编码(支持utf8、gb2312、big5、ansi)：");
			string encode=Console.ReadLine().ToLower();
			if(encode=="utf8")
			{
				encoding=Encoding.UTF8;
			}
			else if(encode=="ansi")
			{
				encoding=Encoding.Default;
			}
			else if(encode=="gb2312")
			{
				encoding=Encoding.GetEncoding(936);
			}
			else if(encode=="big5")
			{
				encoding=Encoding.GetEncoding(950);
			}
			else if(encode=="gbk")
			{
				encoding=Encoding.GetEncoding("GBK");
			}
			
			Console.WriteLine("请输入执行方法：1.随机追加字符串; 2.编辑行；3.重命名文件；4.文本行过滤; 5.启动测试服务器");
			string method=Console.ReadLine();
			if(method=="1")
			{
				randomAppend();
			}
			else if(method=="2")
			{
				editByLine();
			}
            else if (method == "3")
            {
                renameFile();
            }
            else if(method=="4")
            {
                Console.WriteLine("是否要保留不包含B文件内容的行？1.保留; 2.不保留");
                string retain = Console.ReadLine();
                filterRow(retain=="1");
            }
            else if (method == "5") {
                startServer();
            }
			Console.WriteLine("搞定，请输入回车键退出。");
			Console.ReadKey();
		}

        private static void startServer()
        {
            using (HttpListener listerner = new HttpListener())
            {
                listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;//指定身份验证 Anonymous匿名访问
                listerner.Prefixes.Add("http://localhost:8888/");
                listerner.Start();

                Console.WriteLine("测试服务器已启动...");
                while (true)
                {
                    HttpListenerContext ctx = listerner.GetContext();
                    ctx.Response.StatusCode = 200;//设置返回给客服端http状态代码
                    ctx.Response.SetCookie(new Cookie("testCookie", DateTime.Now.ToString()));
                    //使用Writer输出http响应代码
                    using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream))
                    {
                        Console.WriteLine("req reach");
                        writer.WriteLine("<html><head><title>三娃儿是个狗人</title></head><body>");
                        writer.WriteLine("<ul>");
                        foreach (string header in ctx.Request.Headers.Keys)
                        {
                            writer.WriteLine("<li><b>{0}:</b>{1}</li>", header, ctx.Request.Headers[header]);
                        }
                        writer.WriteLine("</ul>");
                        writer.WriteLine("</body></html>");
                        writer.Close();
                        ctx.Response.Close();
                    }
                }
            }
        }
		
		private static void randomAppend()
		{
			string insertContent=null;
			Console.WriteLine("待插入字符串来源：1._i.txt; 2.标题");
			string appendSourceType=Console.ReadLine();
			string extractPattern=null;
			string appendFormat="{0}";
			if(appendSourceType=="1"){
				FileStream insertContentFS=new FileStream(AppDomain.CurrentDomain.BaseDirectory+"/_i.txt",FileMode.Open);
				StreamReader insertContentSR=new StreamReader(insertContentFS, encoding);
				insertContent=insertContentSR.ReadToEnd();
				Console.WriteLine("待插入内容："+insertContent);
			}
			else{
				Console.WriteLine("请输入标题分割符:");
				extractPattern=Console.ReadLine();
				Console.WriteLine("请输入插入格式(直接按回车表示默认<p><strong>{0}</strong></p>)");
				appendFormat=Console.ReadLine();
				appendFormat=string.IsNullOrEmpty(appendFormat)?"<p><strong>{0}</strong></p>":appendFormat;
			}
			
			Console.WriteLine("请输入分隔符(例如</p>, 以字符分割直接按回车，以行分割输入n:");
			string findPatter=Console.ReadLine();
			if(findPatter=="n"){
				findPatter="\r\n";
			}
			
			int randomMax=0;
			Console.WriteLine("在前多少个分隔符中随机插入，输入0不限制范围：");
			randomMax=Int32.Parse(Console.ReadLine());

			Random random=new Random();
			DirectoryInfo dicInfo = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
			FileInfo[] files = dicInfo.GetFiles();
			foreach (FileInfo file in files){
				string fileName=file.Name;
				if(fileName.EndsWith(".txt")&&!fileName.StartsWith("_")){
					if(appendSourceType=="2"){
						int subIndex=fileName.IndexOf(extractPattern);
						insertContent=fileName.Substring(0,subIndex<0?fileName.Length:subIndex);
						insertContent=insertContent.Replace(".txt","");
						insertContent=string.Format(appendFormat,insertContent);
						insertContent+="\r\n";
					}
					
					FileStream fs=new FileStream(file.FullName,FileMode.Open);
					StreamReader sr=new StreamReader(fs, encoding);
					string s=sr.ReadToEnd();
					sr.Close();
					fs.Close();
					
					List<int> indexList=new List<int>();
					for (int i = 0; i<s.Length && (i = s.IndexOf(findPatter, i)) >= 0; i++)
					{
						indexList.Add(i);
					}
					Console.WriteLine("共发现分隔符："+indexList.Count+"个");
					if(indexList.Count>0){
						int iMax=randomMax==0?10000:Math.Min(indexList.Count, randomMax);
						int index=random.Next(0,iMax)%indexList.Count;
						
						StringBuilder result=new StringBuilder();
						result.Append(s.Substring(0, indexList[index]+findPatter.Length));
						result.Append(insertContent);
						result.Append(s.Substring(indexList[index]+findPatter.Length));
						
						StreamWriter writer=new StreamWriter(fileName, false ,Encoding.UTF8);
						writer.Write(result.ToString());
						writer.Flush();
						writer.Close();
					}
				}
			}
		}
		
		private static void editByLine()
		{
			Console.WriteLine("请输入格式化字符串:");
			string format=Console.ReadLine();
			
			int lineGap=0;
			Console.WriteLine("隔多少行编辑，输入0表示逐行编辑, 输入负数表示最大随机多少行编辑：");
			lineGap=Int32.Parse(Console.ReadLine());

			Random random=new Random();
			DirectoryInfo dicInfo = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
			FileInfo[] files = dicInfo.GetFiles();
			foreach (FileInfo file in files){
				string fileName=file.Name;
				if(fileName.EndsWith(".txt")&&!fileName.StartsWith("_")){
					FileStream fs=new FileStream(file.FullName,FileMode.Open);
					StreamReader sr=new StreamReader(fs, encoding);
					string line;
					int gap=lineGap;
					StringBuilder resultBuilder=new StringBuilder();
					while((line=sr.ReadLine())!=null){
						line=line.Trim();
						if(string.IsNullOrEmpty(line)){
							continue;
						}
						
						if(gap<0){
							gap=random.Next(0,1-lineGap);
						}
						
						if(gap==0){
							line=string.Format(format,line);
							gap=lineGap;
						}
						else{
							gap--;
						}
						resultBuilder.Append(line).Append("\r\n");
					}
					sr.Close();
					fs.Close();
					StreamWriter writer=new StreamWriter(fileName, false ,encoding);
					writer.Write(resultBuilder.ToString());
					writer.Flush();
					writer.Close();
				}
			}
		}
		
		private static void renameFile()
		{		
			DirectoryInfo dicInfo = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
			DirectoryInfo[] dirs = dicInfo.GetDirectories();
			foreach (DirectoryInfo dir in dirs)
			{
				FileStream rmFs=new FileStream(dir.FullName+"/_r.txt",FileMode.Open);
				StreamReader rmSR=new StreamReader(rmFs, encoding);
				List<string> rmList=new List<string>();
				string rmContent;
				while((rmContent=rmSR.ReadLine())!=null){
					rmList.Add(rmContent);
				}
				
				FileInfo[] files=dir.GetFiles();
				if((files.Length-1)!=rmList.Count)
				{
					Console.WriteLine("文件名数量与文件数量不符，跳过文件夹："+dir.Name);
					continue;
				}
				int i=0;
				foreach(FileInfo file in files)
				{
					string fileName=file.Name;
					if(fileName!="_r.txt")
					{
                        try
                        {
                            file.MoveTo(dir.Name + "/" + rmList[i] + file.Name.Substring(file.Name.LastIndexOf(".")));
                        }
                        catch(Exception e) 
                        {
                            Console.WriteLine("重命名文件 < " + file.Name + " > 到 < " + rmList[i] + " > 时出现错误：" + e.ToString());
                        }
						i++;
					}
				}
			}
		}

        private static void filterRow(bool retain) 
        {
            StreamReader sourceRS = new StreamReader(new FileStream("source-A.txt", FileMode.Open), encoding);
            List<string> sourceList = new List<string>();
            string sourceLine;
            while ((sourceLine = sourceRS.ReadLine()) != null)
            {
                sourceList.Add(sourceLine);
            }

            StreamReader filterRS = new StreamReader(new FileStream("filter-A.txt", FileMode.Open), encoding);
            List<string> filterList = new List<string>();
            string filterLine;
            while ((filterLine = filterRS.ReadLine()) != null)
            {
                filterList.Add(filterLine);
            }

            StringBuilder resultBuilder = new StringBuilder();
            foreach (var source in sourceList)
            {
                string newSource = source;
                foreach (var filter in filterList)
                {
                    if (newSource.Contains(filter)) 
                    {
                        newSource = newSource.Replace(filter, "");
                    }
                }
                if (retain || newSource!=source)
                {
                    resultBuilder.Append(newSource).Append("\r\n");
                }
            }
            sourceRS.Close();
            filterRS.Close();

            StreamWriter writer = new StreamWriter("target-A.txt", false, encoding);
            writer.Write(resultBuilder.ToString());
            writer.Flush();
            writer.Close();
        }
	}
}